import * as Utils from './utils'
import * as Storage from './storage'

const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)
const app = getApp()

const devHeader = {}

if (!IS_PROD) {
  devHeader.Cookie = 'XDEBUG_SESSION=PHPSTORM'
}

const request = ({ method = 'GET', url = '', data = {}, header = {} }) => {
  return new Promise((resolve, reject) => {
    uni.showLoading()
    uni.request({
      url: app.globalData.baseApi + url,
      data,
      method,
      header: Object.assign({
        'X-Version': app.globalData.version,
        'X-Platform': Utils.getPlatform(),
        'X-Timestamp': Utils.getNowTime(),
        'X-Token': Storage.get(Storage.cacheKey.token)
      }, devHeader, header),
      success(res) {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            resolve(res.data)
          } else {
            reject(res.data)
          }
        } else if (res.statusCode === 401) {
          Utils.clearToken()
          uni.navigateTo({
            url: '/pages/auth/login'
          })
        } else {
          reject(res.data)
        }
      },
      fail(err) {
        reject(err)
      },
      complete() {
        uni.hideLoading()
      }
    })
  })
}

const post = (url = '', data = {}, header = {}) => request({ url, data, method: 'POST', header })
const get = (url = '', data = {}, header = {}) => request({ url, data, method: 'GET', header })

const uploadFile = (url, filePath) => {
  return new Promise((resolve, reject) => {
    uni.showLoading()
    uni.uploadFile({
      url: app.globalData.baseApi + url,
      name: 'file',
      filePath,
      success: res => {
        resolve(res)
      },
      fail: e => {
        reject(e)
      },
      complete() {
        uni.hideLoading()
      }
    })
  })
}

export default {
  request,
  post,
  get,
  uploadFile
}
